<template>
  <div class="app-container">
    <!-- <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="字典名称" prop="dictType">
        <el-select v-model="queryParams.dictType">
          <el-option
            v-for="item in typeOptions"
            :key="item.dictTypeCode"
            :label="item.dictTypeName"
            :value="item.dictTypeCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="字典类型" prop="dictTypeCode">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入字典类型"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:dict:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-close" size="mini" @click="handleClose">关闭</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dataList" height="calc(100% - 100px)">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="字典编码" align="center" width="80" type="index" />
      <el-table-column label="字典标签" align="center" prop="dictName">
      </el-table-column>
      <el-table-column label="字典键值" align="center" prop="dictActualValue" />
      <el-table-column label="字典类型" align="center" prop="dictEnName">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="handleDialog(scope.row)">{{ scope.row.dictEnName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="dictStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.dictStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="updateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:dict:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dictEnName" v-show="dictOptions.length !== 0">
          <el-select v-model="form.dictEnName" placeholder="请选择数据类型" style="width:100%" :disabled="title == '修改字典类型'">
            <el-option v-for="item in dictOptions" :key="item.dictEnName" :label="item.dictName" :value="item.dictEnName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型" prop="dictEnName" v-show="dictOptions.length == 0">
          <el-input v-model="form.dictEnName" placeholder="请输入数据类型" :disabled="title == '修改字典类型'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 配置数据项数值 -->
    <el-dialog title="配置" :visible.sync="openConfig" width="500px" append-to-body>
      <el-form ref="formConfig" :model="formConfig" :rules="rulesConfig" label-width="150px">
        <el-form-item :label="item.dictTypeName" v-for="(item, i) in dictChildTypes" :key="i">
          <!-- v-model="formConfig[item.dictTypeCode]" -->
          <el-input v-model="formConfig[item.dictTypeCode]" style="width: 50%" @input="$forceUpdate()" /><span> {{
            item.unit }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormConfig">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Data",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 默认字典类型
      defaultDictType: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认",
        },
        {
          value: "primary",
          label: "主要",
        },
        {
          value: "success",
          label: "成功",
        },
        {
          value: "info",
          label: "信息",
        },
        {
          value: "warning",
          label: "警告",
        },
        {
          value: "danger",
          label: "危险",
        },
      ],
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        dictStatus: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictName: [
          { required: true, message: "数据标签不能为空", trigger: "blur" },
        ],
        dictActualValue: [
          { required: true, message: "数据键值不能为空", trigger: "blur" },
        ],
        dictEnName: [
          { required: true, message: "字典类型不能为空", trigger: "blur" },
        ],
      },
      formConfig: {},
      rulesConfig: {
        sadr: [{ required: true, message: "不能为空", trigger: "blur" }],
        agcresp: [{ required: true, message: "不能为空", trigger: "blur" }],
        dead: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      //是否显示配置项弹窗
      openConfig: false,
      configData: [],
      dictChildTypes: [],
      oneConfigRow: {},
      dictOptions: [],
      arrSlice: ""
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询字典类型详细 */

    /** 查询字典类型列表 */
    getTypeList() {
      this.queryParams.dictType =
        this.$route.params && this.$route.params.dictId;
      this.getList();
    },
    /** 查询字典数据列表 */
    getList() {
      this.loading = true;
      this.queryParams.dictType =
        this.$route.params && this.$route.params.dictId;
      let postData = {
        ...this.queryParams,
      };
      this.$httpGet(window.api.getOneLevelDicts, postData)
        .then((response) => {
          if (response.code == 200) {
            this.dataList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        })
        .catch((err) => { });
      this.getDictData()
    },
    /**
     * 查询字典类型数据项
     */
    getDictData() {
      let a = [], b = [], c = "";
      a = this.queryParams.dictType.split("_")
      b = a.slice(0, a.length - 1)
      c = b.join("_")
      this.arrSlice = "_" + a.slice(a.length - 1, a.length)
      let postData = {
        pageNum: 1,
        pageSize: 9999,
        dictType: c
      }
      this.$httpGet(window.api.getOneLevelDicts, postData)
        .then((response) => {
          if (response.code && response.rows) {
            this.dictOptions = response.rows
          }
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openConfig = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dictCode: undefined,
        dictName: undefined,
        dictActualValue: undefined,
        cssClass: undefined,
        dictSort: 0,
        dictStatus: "0",
      };
      this.formConfig = {
        dictCode: undefined,
        dictName: undefined,
        dictActualValue: undefined,
        cssClass: undefined,
        dictSort: 0,
        dictStatus: "0",
      };
      this.resetForm("form");
      this.resetForm("formConfig");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/system/dict" };
      this.$tab.closeOpenPage(obj);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dictType = this.defaultDictType;
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加字典数据";
      this.form.dictType = this.queryParams.dictType;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.dictCode);
      this.single = selection.length != 1;
      title;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let postData = {
        dictNo: row.dictNo,
        dictType: row.dictType,
      };
      this.$httpGet(window.api.getDictData, postData)
        .then((response) => {
          if (response.code == 200) {
            if (this.dictOptions.length) {
              let splitArr = response.data.dictEnName.split('_')
              splitArr.splice(splitArr.length - 1, 1)
              response.data.dictEnName = splitArr.join('_')
            }
            this.form = response.data;
            this.open = true;
            this.title = "修改字典类型";
          }
        })
        .catch((err) => { });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dictOptions.length !== 0) {
            this.form.dictEnName = this.form.dictEnName + this.arrSlice
          }
          this.$httpPost(window.api.saveDictData, this.form).then(
            (response) => {
              if (response.code == 200) {
                if (this.form.dictNo != undefined) {
                  this.$modal.msgSuccess("修改成功");
                } else {
                  this.$modal.msgSuccess("新增成功");
                }
                this.open = false;
                this.getList();
              }
            }
          );
        }
      });
    },
    getSaveForm(item) {
      let coal = JSON.parse(JSON.stringify(this.oneConfigRow));
      let a = {};
      let c = item.dictTypeCode.split("_");

      a = {
        dictType: coal.dictType + "_" + c[c.length - 1],
        dictName: item.dictName,
        dictEnName: coal.dictEnName + "_" + c[c.length - 1],
        unit: item.unit,
      };
      this.$httpPost(window.api.saveDictData, a).then((response) => {
        if (response.code == 200) {
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const dictTypes = row.dictType;
      this.$modal
        .confirm('是否确认删除字典标签为"' + dictTypes + '"的数据项？')
        .then(() => {
          return this.$httpGet(window.api.deleteDictData, {
            dictNo: row.dictNo,
            dictType: row.dictType,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$store.dispatch("dict/removeDict", this.queryParams.dictType);
        })
        .catch(() => { });
    },
    /** 字典子类型数据配置弹窗 */
    handleDialog(row) {
      this.oneConfigRow = row;
      let postData = {
        pageNum: 1,
        pageSize: 10,
        dictTypeCode: this.queryParams.dictType,
      };
      let list = [];
      this.$httpGet(window.api.getDictTypes, postData)
        .then((response) => {
          if (response.code == 200) {
            response.rows.map((item) => {
              if (this.queryParams.dictType !== item.dictTypeCode) {
                list.push(item);
              }
            });
            this.getConfigData(list, row);
          }
        })
        .catch((err) => { });
    },
    getConfigData(list, rowData) {
      this.dictChildTypes = [];
      let u = {
        PHY_UNIT_TYPE_SADR: "%",
        PHY_UNIT_TYPE_DEAD: "Hz",
        PHY_UNIT_TYPE_AGCRESP: "秒",
      };

      list.forEach(async (item, index) => {
        let b = "";
        if (item.dictTypeName == "标准调节速率比例") {
          b = "_SADR";
        } else if (item.dictTypeName == "标准agc响应时间") {
          b = "_AGCRESP";
        } else if (item.dictTypeName == "调频死区") {
          b = "_DEAD";
        }
        item.unit = u[item.dictTypeCode];
        let obj = {};
        let rows = await this.getChildrenData(item);
        rows.map((res) => {
          if (
            rowData.dictEnName + b == res.dictEnName &&
            item.dictTypeCode == res.dictType
          ) {
            obj = res;
          }
        });
        this.dictChildTypes.push({ ...obj, ...item });
        this.dictChildTypes.sort((a, b) => {
          return a.dictNo - b.dictNo;
        });
        this.formConfig[item.dictTypeCode] = obj.dictName;
      });

      this.openConfig = true;
    },
    // 获取当前机组下子类型数据
    async getChildrenData(item) {
      let data = await this.$httpGet(window.api.getOneLevelDicts, {
        dictType: item.dictTypeCode,
      }).then((response) => {
        if (response.code == 200) {
          return response.rows;
        }
      });
      return data;
    },
    submitFormConfig() {
      this.$refs["formConfig"].validate((valid) => {
        if (valid) {
          let oldData = JSON.parse(JSON.stringify(this.dictChildTypes));
          oldData.map((item1) => {
            Object.keys(this.formConfig).map((item2, index2) => {
              if (item1.dictTypeCode == item2) {
                item1.dictName = Object.values(this.formConfig)[index2];
              }
            });
          });
          oldData.forEach((item, index) => {
            if (item?.dictEnName) {
              this.$httpPost(window.api.saveDictData, item).then((response) => {
                if (response.code == 200) {
                  // this.$modal.msgSuccess(response.msg);
                  this.getList();
                }
              });
            } else {
              this.getSaveForm(item);
            }
          });
          // this.$modal.msgSuccess("操作成功");
          this.openConfig = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  height: 100%
}
</style>